<template>
  <div>
    <Category :scene="scene"></Category>

    <el-card style="margin: 10px 0px">
      <div v-show="scene == 0">
        <el-button type="primary" size="default" icon="Plus" :disabled="categoryStore.c3Id ? false : true"
          @click="addAttr">
          添加属性
        </el-button>

        <el-table border style="margin: 10px 0px" :data="attrArr">
          <el-table-column type="index" label="序号" width="100px" align="center"></el-table-column>
          <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row }">
              <el-tag v-for="item in row.attrValueList" :key="item.id" style="margin: 5px">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="id" label="操作" header-align="left" width="120px">
            <template #="{ row }">
              <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>

              <el-popconfirm :title="`您确定要删除${row.attrName}吗？`" width="280px" icon="Delete" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input placeholder="请输入属性名称" v-model="attrObjParam.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button :disabled="attrObjParam.attrName ? false : true" type="primary" size="default" icon="Plus"
          @click="addAttrValue">
          添加属性值
        </el-button>

        <el-button type="primary" size="default" icon="Delete" @click="cancel">
          取消
        </el-button>

        <el-table border style="margin: 10px 0px" :data="attrObjParam.attrValueList">
          <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
          <el-table-column label="属性性名称">

            <template #="{ row, $index }">
              <el-input :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row, $index)"
                v-model="row.valueName" placeholder="请输入属性值名称" size="small"></el-input>

              <dev v-else @click="toEdit(row, $index)">{{ row.valueName }}</dev>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ $index }">
              <el-button type="primary" size="small" icon="Delete"
                @click="attrObjParam.attrValueList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" @click="save"
          :disabled="attrObjParam.attrValueList.length > 0 ? false : true">保存</el-button>

        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import useCategoryStore from '@/store/modules/category'
import type { AttrObj, AttrResponse, AttrValueObj } from '@/api/product/attr/type'
import { reqAttr } from '@/api/product/attr'
import { ElButton, ElMessage } from 'element-plus'
import { reqSaveAttr, reqDeleteAttr } from '@/api/product/attr'
const categoryStore = useCategoryStore()

let attrArr = ref<AttrObj[]>([])

// 卡片内容切换  0显示tab 1显示编辑
let scene = ref<number>(0)

let attrObjParam = reactive<AttrObj>({

  attrName: "",
  categoryId: "",
  categoryLevel: 3,
  attrValueList: []
})

let inputArr = ref<any>([])
watch(
  () => categoryStore.c3Id,
  () => {
    attrArr.value = []
    if (!categoryStore.c3Id) return
    getAttr()
  },
)

const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  let result: AttrResponse = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code === 200) {
    attrArr.value = result.data

    attrArr.value.forEach(
      (item) => (item.attrValueList = item.attrValueList.slice(0, 20)),
    )
  }
}
const addAttr = () => {
  Object.assign(attrObjParam, {
    attrName: "",
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,
    attrValueList: []
  })
  scene.value = 1

}

const updateAttr = (row: AttrObj) => {

  Object.assign(attrObjParam, JSON.parse(JSON.stringify(row)))
  scene.value = 1

}

const cancel = () => {
  scene.value = 0
}

const addAttrValue = () => {

  attrObjParam.attrValueList.push({

    valueName: "",
    attrId: attrObjParam.id,
    flag: true

  })

  nextTick(() => {
    inputArr.value[attrObjParam.attrValueList.length - 1].focus()
  })
}
const save = async () => {


  let result: any = await reqSaveAttr(attrObjParam)


  if (result.code === 200) {
    scene.value = 0
    ElMessage.success(attrObjParam.id ? '修改成功' : '添加成功')
    getAttr()
  } else {
    ElMessage.error(attrObjParam.id ? '修改失败' : '添加失败')
  }
}

const toLook = (attrValue: AttrValueObj, $index: number) => {



  if (attrValue.valueName.trim() == '') {
    attrObjParam.attrValueList.splice($index, 1)
    ElMessage.error('属性值名称不能为空')
    return;
  }

  let repeat = attrObjParam.attrValueList.find((item) => {
    if (item != attrValue) {
      // attrObjParam.attrValueList.splice($index,1)
      // ElMessage.error('属性值名称不能重复')
      return item.valueName == attrValue.valueName;
    }
  })
  if (repeat) {
    attrObjParam.attrValueList.splice($index, 1)
    ElMessage.error('属性值名称不能重复')
    return;
  }

  attrValue.flag = false
}

const toEdit = (attrValue: AttrValueObj, $index: number) => {
  attrValue.flag = true

  nextTick(() => {

    inputArr.value[$index].focus()
  })
}

const deleteAttr = async (attrId: number) => {
  let result: any = await reqDeleteAttr(attrId);
  if (result.code === 200) {
    ElMessage.success('删除成功')
    getAttr()
  } else {
    ElMessage.error('删除失败')
  }
}

onBeforeUnmount(() => {
  //清空仓库的数据
  categoryStore.$reset()

})
</script>

<style scoped></style>
